'use strict'

import React from 'react'
import ReactDOM from 'react-dom'
import {
  CircularProgress
} from '@material-ui/core'

import LoginBox from './loginBox'
import MainView from './main'

const electron = window.require('electron');

class MainApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loginMsg: '',
      loading: false,
      logined: false,
      chunnels: [],
    }
  }

  componentDidMount() {
    window.addEventListener('resize', () => {
      this.forceUpdate()
    })
    electron.ipcRenderer.on('loginFailure', () => {
      this.setState({ loginMsg: '登陆失败!'})
    })
    electron.ipcRenderer.on('loginSuccess', () => {
      this.setState({
        loading: true,
        logined: true,
      })
      setTimeout(() => {
        this.setState({
          loading: false,
        })
      }, 1000)
    })
  }

  handleExit() {
    electron.ipcRenderer.send("exitApp")
  }

  handleLogin(usr, pwd) {
    electron.ipcRenderer.send("login", {usr: usr, pwd: pwd})
  }

  render() {
    if (this.state.loading === true) {
      return (
        <div>
          <CircularProgress
            style={{
              position: 'absolute',
              left: window.innerWidth / 2 - 40,
              top: window.innerHeight / 3 - 40, 
              color: '#6264CC'
            }}
            value={100}
            size={80} thickness={4} />
          <CircularProgress
            style={{
              position: 'absolute',
              left: window.innerWidth / 2 - 20,
              top: window.innerHeight / 3 - 20,
            }}
            color='secondary'
            value={30}
            size={40} thickness={4} />
          <CircularProgress
            style={{
              position: 'absolute',
              left: window.innerWidth / 2 - 10,
              top: window.innerHeight / 3 - 10,
            }}
            value={30}
            size={20} thickness={4} />
        </div>
      )
    }
    if (this.state.logined === true) {
      return (
        <MainView
          onExit={() => this.handleExit()}
          chunnels={this.state.chunnels}
        />
      )
    }
    return (
      <LoginBox
        msg={this.state.loginMsg}
        onExit={() => this.handleExit()}
        onLogin={(usr, pwd) => this.handleLogin(usr, pwd)}
      />
    )
  }
}

ReactDOM.render((<MainApp />), document.getElementById('content'))